package com.chinaunicom.emergency.aspect;

import com.chinaunicom.emergency.model.YjglUser;
import com.chinaunicom.emergency.repository.UsersRepository;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

@Aspect
@Log4j2
@Component
public class TokenAspect {

    @Autowired
    private UsersRepository usersRepository;

    @Pointcut("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    private void token() {
    }

    @AfterReturning(returning = "obj", pointcut = "token()")
    public void doAfterReturning(ResponseEntity<OAuth2AccessToken> obj) throws Exception {
        String userName = (String)obj.getBody().getAdditionalInformation().get("user_name");
        if(userName != null){
            String accessToken = obj.getBody().getValue();
            YjglUser user = usersRepository.findByUserNameAndIsSoftDel(userName,0);
            user.setAccessToken(accessToken);
            usersRepository.saveAndFlush(user);
            log.info("登录获得到的token：{},{}",userName,accessToken);
        }
    }
}
